package com.settlement.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.enums.LogRecordEnum;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.common.util.RequestUtils;
import com.settlement.system.handler.xxljob.XxlJobSampleHandler;
import com.settlement.system.model.entity.SysLogRecord;
import com.settlement.system.model.entity.SysStoreAccount;
import com.settlement.system.model.form.StoreAccountForm;
import com.settlement.system.model.query.StoreAccountPageQuery;
import com.settlement.system.model.vo.StoreAccountSyncVo;
import com.settlement.system.service.SysLogRecordService;
import com.settlement.system.service.SysStoreAccountService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 店铺账号表 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2023-08-25
 */
@RestController
@RequestMapping("/api/v1/storeAccount")
@RequiredArgsConstructor
public class SysStoreAccountController {

    @Value("${system.config.secret}")
    private String secret;

    @Value("${system.config.appId}")
    private String appId;
    private final SysStoreAccountService sysStoreAccountService;

    private final SysLogRecordService logRecordService;

    @Operation(summary = "店铺账号分页列表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/page")
    public PageResult<SysStoreAccount> getStoreAccountPage(
            @ParameterObject StoreAccountPageQuery queryParams
    ) {
        Page<SysStoreAccount> result = sysStoreAccountService.getStoreAccountPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "保存店铺账号", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping
    @PreAuthorize("@ss.hasPerm('sys:storeAccount:save')")
    @PreventDuplicateSubmit
    public Result<?> saveStoreAccount(
            @RequestBody @Valid StoreAccountForm storeForm
    ) {
        boolean result = sysStoreAccountService.saveStoreAccount(storeForm);
        return Result.judge(result);
    }

    @Operation(summary = "店铺账号表单数据", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/{storeAccountId}/form")
    public Result<SysStoreAccount> getStoreAccountFormData(
            @Parameter(description = "店铺账号ID") @PathVariable Long storeAccountId
    ) {
        SysStoreAccount storeAccount = sysStoreAccountService.getStoreAccountFormData(storeAccountId);
        return Result.success(storeAccount);
    }

    @Operation(summary = "删除店铺账号", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:storeAccount:delete')")
    public Result<?> deleteStores(
            @Parameter(description = "店铺账号ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = sysStoreAccountService.deleteStoreAccounts(ids);
        return Result.judge(result);
    }

    @Operation(summary = "RPA通过平台和账单类型提取账号信息")
    @GetMapping("/getAccountList/{platform}")
    public Result<?> getAccountList(HttpServletRequest request,
            @Parameter(description = "平台") @PathVariable String platform,
            @Parameter(description = "类型") @RequestParam(value = "type") String type
    ) {
        Result<?> result = RequestUtils.resolveAppToken(request, secret, appId);
        if (!Result.isSuccess(result)) {
            return result;
        }
        return Result.success(sysStoreAccountService.getAccountList(platform, type));
    }

    @Operation(summary = "同步账号和密码")
    @PostMapping("/sync")
    public Result<?> sync(HttpServletRequest request, @RequestBody List<StoreAccountSyncVo> syncVoList) {
        Result<?> result = RequestUtils.resolveAppToken(request, secret, appId);
        if (!Result.isSuccess(result)) {
            return result;
        }
        sysStoreAccountService.sync(syncVoList);
        return Result.success();
    }

    @Operation(summary = "RPA通过拼接key获取任务ID")
    @GetMapping("/getJobId/{key}")
    public Result<?> getAccountList(HttpServletRequest request, @Parameter(description = "拼接key") @PathVariable String key) {
        Result<?> result = RequestUtils.resolveAppToken(request, secret, appId);
        if (!Result.isSuccess(result)) {
            return result;
        }
        List<SysLogRecord> records = logRecordService.list(new LambdaQueryWrapper<SysLogRecord>().eq(SysLogRecord::getJobKey, key));
        records = records.stream().filter(item -> !Objects.equals(LogRecordEnum.SUCCESS.getLabel(), item.getResult())).toList();
        if(records.size() > 0){
            return Result.success(records.get(0).getId());
        }
        return Result.success(0);
    }

}
